#include <vtkNew.h>
#include <vtkImageData.h>
#include <vtkRectilinearGrid.h>
#include <vtkRectilinearGridWriter.h>
#include <vtkSmartPointer.h>
#include <vtkStructuredGrid.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkColorTransferFunction.h>
#include <vtkPiecewiseFunction.h>
#include <vtkSmartVolumeMapper.h>
#include <vtkAxesActor.h>
#include <vtkAutoInit.h>
#include <vtkImageActor.h>
#include <vtkImageMapper.h>
#include <vtkVolume.h>
#include <vtkVolumeProperty.h>
#include <vtkPolyDataMapper.h>
#include <vtkUnsignedCharArray.h>
#include <vtkStructuredGrid.h>
#include <vtkActor.h>
#include <vtkCellData.h>
#include <vtkProperty.h>
#include <vtkDataSetMapper.h>
#include <vtkImageMapper3D.h>

VTK_MODULE_INIT(vtkRenderingOpenGL2);
VTK_MODULE_INIT(vtkInteractionStyle);
VTK_MODULE_INIT(vtkRenderingVolumeOpenGL2)

// 创建单层格网的函数
vtkSmartPointer<vtkActor> CreateGridLayer(
    int dimensions[3], // 格网尺寸（x,y,z方向的点数）
    double origin[3],  // 格网原点
    double spacing[3], // 格网间距
    double color[3])   // 格网颜色
{
    // 1. 创建结构化格网
    vtkSmartPointer<vtkStructuredGrid> grid = vtkSmartPointer<vtkStructuredGrid>::New();
    grid->SetDimensions(dimensions);

    // 2. 生成格网点坐标
    vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
    for (int k = 0; k < dimensions[2]; k++)
    {
        for (int j = 0; j < dimensions[1]; j++)
        {
            for (int i = 0; i < dimensions[0]; i++)
            {
                double x = origin[0] + i * spacing[0];
                double y = origin[1] + j * spacing[1];
                double z = origin[2] + k * spacing[2];
                points->InsertNextPoint(x, y, z);
            }
        }
    }
    grid->SetPoints(points);

    // 3. 为格网单元设置颜色
    vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New();
    colors->SetNumberOfComponents(3);
    colors->SetName("CellColors");

    int numCells = grid->GetNumberOfCells();
    for (int i = 0; i < numCells; i++)
    {
        // 根据单元格索引计算渐变颜色 (示例: 从蓝色到红色)
        double ratio = static_cast<double>(i) / (numCells - 1); // 0.0 to 1.0
        unsigned char r = static_cast<unsigned char>(ratio * 255);
        unsigned char g = 0;
        unsigned char b = static_cast<unsigned char>((1.0 - ratio) * 255);

        colors->InsertNextTuple3(r, g, b);
    }
    grid->GetCellData()->SetScalars(colors);

    // 4. 创建Actor
    vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New();
    mapper->SetInputData(grid);

    vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
    actor->SetMapper(mapper);
    actor->GetProperty()->SetEdgeVisibility(1); // 显示网格线
    actor->GetProperty()->SetLineWidth(1.5);    // 线宽
    actor->GetProperty()->SetOpacity(0.7);      // 透明度

    return actor;
}


vtkSmartPointer<vtkActor> CreateGridLayerWithImageData(
    int dimensions[3], 
    double origin[3],  
    double spacing[3], 
    double color[3])   
{
    // 1. 创建图像数据
    vtkSmartPointer<vtkImageData> imageData = vtkSmartPointer<vtkImageData>::New();
    imageData->SetDimensions(dimensions);
    imageData->SetOrigin(origin);
    imageData->SetSpacing(spacing);

    // 2. 创建颜色数据（如果需要）
    // ...颜色设置逻辑...

    // 3. 创建Mapper和Actor
    vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New();
    mapper->SetInputData(imageData);

    vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
    actor->SetMapper(mapper);
    actor->GetProperty()->SetEdgeVisibility(1);
    actor->GetProperty()->SetLineWidth(1.5);
    actor->GetProperty()->SetOpacity(0.7);

    return actor;
}
vtkSmartPointer<vtkVolume> CreateVolume(){
        // 1. 创建并配置vtkImageData
    vtkSmartPointer<vtkImageData> imageData = vtkSmartPointer<vtkImageData>::New();
    // 几何属性设置（20x20x20的3D体数据）
    imageData->SetDimensions(200, 200, 200);              // 体素尺寸
    imageData->SetOrigin(0, 0, 0);                     // 原点坐标
    imageData->SetSpacing(1.0, 1.0, 1.0);              // 体素间距（1单位/体素）
    //必须调用，否则执行后续代码，内存不可用
    imageData->AllocateScalars(VTK_UNSIGNED_SHORT, 1); // 分配内存

    // 2. 填充数据：创建一个中心为高值的球体形状（模拟3D结构）
    unsigned short *data = static_cast<unsigned short *>(imageData->GetScalarPointer());
    int dims[3];
    imageData->GetDimensions(dims);

    for (int z = 0; z < dims[2]; z++)
    {
        for (int y = 0; y < dims[1]; y++)
        {
            for (int x = 0; x < dims[0]; x++)
            {
                // 计算到中心的距离
                double cx = dims[0] / 2.0;
                double cy = dims[1] / 2.0;
                double cz = dims[2] / 2.0;
                double dist = sqrt(pow(x - cx, 2) + pow(y - cy, 2) + pow(z - cz, 2));

                // 距离中心越近，值越高（0-4095）
                unsigned short value = static_cast<unsigned short>(
                    std::max(0.0, 4095.0 * (1.0 - dist / 10.0)));
                *data++ = value;
            }
        }
    }

    // 3. 配置体绘制参数
    // 3.1 颜色传递函数（值->颜色）
    vtkSmartPointer<vtkColorTransferFunction> colorFunc =
        vtkSmartPointer<vtkColorTransferFunction>::New();
    colorFunc->AddRGBPoint(0, 0.0, 0.0, 0.0);    // 低值（黑色）
    colorFunc->AddRGBPoint(1000, 1.0, 0.0, 0.0); // 中低值（红色）
    colorFunc->AddRGBPoint(3000, 1.0, 1.0, 0.0); // 中高值（黄色）
    colorFunc->AddRGBPoint(4095, 1.0, 1.0, 1.0); // 高值（白色）

    // 3.2 不透明度传递函数（值->透明度）
    vtkSmartPointer<vtkPiecewiseFunction> opacityFunc =
        vtkSmartPointer<vtkPiecewiseFunction>::New();
    opacityFunc->AddPoint(0, 0.0);    // 低值完全透明
    opacityFunc->AddPoint(500, 0.1);  // 开始显示
    opacityFunc->AddPoint(4095, 0.8); // 高值半透明

    // 3.3 体属性设置
    vtkSmartPointer<vtkVolumeProperty> volumeProperty = vtkSmartPointer<vtkVolumeProperty>::New();
    volumeProperty->SetColor(colorFunc);
    volumeProperty->SetScalarOpacity(opacityFunc);
    volumeProperty->ShadeOn(); // 启用阴影效果

    // 3.4 体绘制映射器
    vtkSmartPointer<vtkSmartVolumeMapper> volumeMapper =
        vtkSmartPointer<vtkSmartVolumeMapper>::New();
    volumeMapper->SetInputData(imageData);

    // 3.5 体绘制Actor
    vtkSmartPointer<vtkVolume> volume = vtkSmartPointer<vtkVolume>::New();
    volume->SetMapper(volumeMapper);
    volume->SetProperty(volumeProperty);
    return volume;
}

int main(int argc, char *argv[])
{
    vtkNew<vtkRenderer> lrender;
    lrender->SetBackground(0.0, 0.2, 0.4);
    lrender->SetViewport(0, 0, 0.33, 1);
    // 在左边1/3上绘制vtkImageData
     vtkSmartPointer<vtkImageData> imageData = vtkSmartPointer<vtkImageData>::New();
     imageData->SetDimensions(10, 10, 10);
     imageData->SetSpacing(1.0, 1.0, 1.0);

    vtkSmartPointer<vtkDataSetMapper> imageDataMapper = vtkSmartPointer<vtkDataSetMapper>::New();
    imageDataMapper->SetInputData(imageData);

    vtkSmartPointer<vtkActor> imageDataActor = vtkSmartPointer<vtkActor>::New();
    imageDataActor->SetMapper(imageDataMapper);

    // vtkSmartPointer<vtkVolumeMapper> imageMapper3d = vtkSmartPointer<vtkVolumeMapper>::New();

    vtkSmartPointer<vtkImageMapper> imageMapper = vtkSmartPointer<vtkImageMapper>::New();
    // imageMapper3d->SetInputData(imageData);
   
    vtkSmartPointer<vtkImageActor> imageActor = vtkSmartPointer<vtkImageActor>::New();
    // imageActor->SetMapper(imageMapper3d);

    //设置边缘是否可见
    imageDataActor->GetProperty()->SetEdgeVisibility(1);
    // imageDataActor->GetProperty()->SetLineWidth(1.5);
    imageDataActor->GetProperty()->SetOpacity(0.7);
    lrender->AddActor(imageDataActor);
    // lrender->AddActor(imageActor);


    // 4. 添加坐标轴（辅助理解空间坐标）
    vtkSmartPointer<vtkAxesActor> axes = vtkSmartPointer<vtkAxesActor>::New();
    axes->SetTotalLength(5, 5, 5); // 坐标轴长度
    axes->SetCylinderRadius(0.1);  // 轴半径

    lrender->ResetCamera();
    // lrender->AddActor(axes);
    // lrender->AddActor(volume);
    // 替换main函数中的第174行为以下内容：
    int dim[3] = {10, 10, 10};
    double origin[3] = {0, 0, 0};
    double spacing[3] = {1, 1, 1};
    double color[3] = {0.3, 0.3, 1.0};

    vtkSmartPointer<vtkActor> grid = CreateGridLayer(dim, origin, spacing, color);
    // lrender->AddActor(grid);

    vtkNew<vtkRenderer> crenderer;
    crenderer->SetBackground(0.2, 0.3, 0.4);
    // 设置crenderder的范围为屏幕的中间1/3
    crenderer->SetViewport(0.33, 0, 0.67, 1);
    crenderer->AddActor(CreateVolume());
    crenderer->ResetCamera();
    vtkNew<vtkRenderWindow> renderWindow;

    vtkNew<vtkRenderer> renderer;
    renderer->SetBackground(0.4, 0.1, 0.6);
    renderer->SetViewport(0.67, 0, 1, 1);
    vtkSmartPointer<vtkActor> grid1 = CreateGridLayerWithImageData(dim, origin, spacing, color);
    renderer->AddActor(grid1);
    renderer->ResetCamera();

    renderWindow->AddRenderer(lrender);
    renderWindow->AddRenderer(crenderer);
    renderWindow->AddRenderer(renderer);

    vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
    renderWindowInteractor->SetRenderWindow(renderWindow);

    vtkNew<vtkInteractorStyleTrackballCamera> style;
    renderWindowInteractor->SetInteractorStyle(style);

    renderWindow->Render();
    renderWindowInteractor->Initialize();
    renderWindowInteractor->Start();
    return EXIT_SUCCESS;
}